#define LOG_TAG "resource"

#include "endpoint.h"
int g_frequency = 10;

void res_frequence(restful_request_t * request, REQ_ENV_HANDLE req_env)
{
    char property[200] = {0};
    char buf[256];
    LOG2("Enter: method = %s", rest_action_str(request->action));
    if(request->query)  
        find_key_value(request->query, strlen(request->query), "pt", property, sizeof(property), '&');

    // only support single property: "value"
    if(property[1] && strcmp(property, "value") != 0)
    {
        wa_set_response_status(req_env, BAD_REQUEST_4_00);
        return;
    }

    if(request->action == T_Get)
    {
        // query on property "value"
        if(property[1])
        {
            snprintf(buf, sizeof(buf), "%d", g_frequency);
            wa_set_response(req_env, CONTENT_2_05, TEXT_PLAIN, strlen(buf), buf);
            return;
        }

        cJSON * j_root = cJSON_CreateObject();
        cJSON_AddNumberToObject(j_root, "value", g_frequency);
        char * payload = cJSON_Print(j_root);
        cJSON_Delete(j_root);
        wa_req_env_handover_payload(req_env, CONTENT_2_05, IA_APPLICATION_JSON, strlen(payload), (const char**)&payload);
        return;
    }

    if(request->action == T_Put && property[1])
    {
        g_frequency = atoi(request->payload);
        WALOG("frequence changed to %d", g_frequency);
        wa_set_response_status(req_env, CHANGED_2_04);
        return;
    }

    wa_set_response_status(req_env, BAD_REQUEST_4_00);
}


void res_count( restful_request_t * request, REQ_ENV_HANDLE req_env)
{
    WALOG("Recieved: %s", request->url);
    wa_set_response_status(req_env, BAD_REQUEST_4_00);
}